import Reflux from 'reflux';
import Actions from './Actions';
import update from 'react-addons-update';
import Utils from "../../../../utils/index";

import { Control } from 'react-keeper'
import { Toast, Modal } from 'antd-mobile';

import DB from '../../../../app/db';
import StorageUtils from "../../../../app/storage";

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    doorId: '',
    isLoading: true,
    authInfo: {},
    door: {},
    isReAuth: false,
  },

  customInit(doorId) {
    this.data.isLoading = true;
    this.data.isReAuth = false;
    this.data.doorId = doorId;
    this.updateComponent();
    this.getAuth();
  },

  onReAuth() {
    let t = this;
    DB.DoorAuth.reAuth({id: t.data.authInfo.data.proprietorAuthId}).then(
      function (content) {
        if (content) {
          t.data = update(t.data, {
            isReAuth: {$set: true},
            isReAuthSuccess: {$set: true}
          });
        } else {
          t.data = update(t.data, {
            isReAuth: {$set: true},
            isReAuthSuccess: {$set: false}
          });
        }
        t.updateComponent();
      },
      function (error) {
        t.data = update(t.data, {
          isReAuth: {$set: true},
          isReAuthSuccess: {$set: false}
        });
        t.updateComponent();
      }
    );
  },

  getAuth() {
    let t = this;
    DB.DoorAuth.getAuth({doorId: t.data.doorId}).then(
      function (content) {
        if (content && content.proprietorAuthId !== null) {
          t.data.authInfo = update(t.data.authInfo, {
            success: {$set: true},
            data: {$set: content}
          });
          t.initDoorInfo();
        } else {
          t.data.authInfo = update(t.data.authInfo, {
            success: {$set: false},
            data: {}
          });
        }
        t.data.isLoading = false;
        t.updateComponent();
      },
      function (error) {
        t.data.authInfo = update(t.data.authInfo, {
          success: {$set: false},
          message: {$set: error}
        });
        t.data.isLoading = false;
        t.updateComponent();
      }
    );
  },

  initDoorInfo() {
    let t = this;
    DB.DoorAuth.findDoorInfoById({id: this.data.doorId}).then(
      function (content) {
        if (content) {
          t.data.door = content;
          t.updateComponent();
        }
      },
      function (error) {
        console.log(error);
      }
    );
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }

});
